package fr.umlv.rtsjtaskserver.server;

import java.util.ArrayList;
import java.util.List;

import javax.realtime.AsyncEventHandler;
import javax.realtime.OneShotTimer;
import javax.realtime.PriorityParameters;
import javax.realtime.RealtimeThread;
import javax.realtime.RelativeTime;

/**
 * This class implements a simple asynchronous task scheduling algorithm : <b>Background Scheduling</b>
 * The scheduling policy is to launch asynchronous task when the processor is free.
 * Through buildTimer method, each {@link AsyncEventHandler} has been affected a low priority. So you are guaranteed
 * that these asynchronous tasks won't interrupt the periodic scheduling.
 * 
 * This policy is not very efficient, because asynchronous tasks might not be released in time.
 *     
 * @author Moreau Alan
 */
public class BackgroundScheduling {

	private static int LOWEST_PRIORITY = RealtimeThread.MIN_PRIORITY;
	
	/**
	 * Build a list of timers according to background scheduling
	 * Each {@link AsyncEventHandler} will have a low priority to avoid
	 * conflict with periodic task  
	 * 
	 * @param handlers
	 * @param times
	 * 
	 * @return a list of {@link OneShotTimer}
	 */
	public static List<OneShotTimer> buildTimer(
			List<AsyncEventHandler> handlers, List<RelativeTime> times) {
		final int nbrHdl = handlers.size();
		if (times.size() != nbrHdl)
			throw new IllegalArgumentException(
					"Bad association between handlers and timers");

		final List<OneShotTimer> timers = new ArrayList<OneShotTimer>();
		for (int i = 0; i < nbrHdl; i++) {
			AsyncEventHandler currentHandler = handlers.get(i);
			currentHandler.setSchedulingParameters(new PriorityParameters(
					LOWEST_PRIORITY));
			timers.add(new OneShotTimer(times.get(i), currentHandler));
		}

		return timers;
	}
}
